# -*- coding: utf-8 -*-
import md5, time, random
from os import environ
import re

#from pycube.core import psql
#from pycube.core.sql.model import column
#from pycube.core.sql.types import *



#Session class***************************************************
class sess:
    def __init__ ( self, environ, cookie, psql, write ):
        self.write = write

        #Define a postgres connection
        self.psql = psql
        self.saveInterval = '2:00:00'

        self.environ = environ
        #Generating new session hash
        self.id = md5.new( str( time.time() + random.random() ) ).hexdigest()

        self.lastEntrance = None
        self.done = False
        #generating new time

        self.cookie = cookie
        #lt = time.localtime(time.time()+1200)
        #self.time = "%04d-%02d-%02d %02d:%02d:%02d.%03d" % (lt[0], lt[1], lt[2], lt[3], lt[4], lt[5],lt[7])
        self.opera = False


    #Initialize session*******************************************    
    def start( self ):
        #Getting cookies
        #write( environ )
        data = re.match( '.*?Opera.*?' , self.environ['HTTP_USER_AGENT'], re.DOTALL )
        if data:
            self.opera = True


        self.session_id = self.cookie.get( 'session_id' )

        if self.session_id:
            #self.write(self.session_id)
            result = self.psql.select( "SELECT name,user_id,expire,save,last_action \
                                        FROM \"session\" WHERE expire > localtimestamp \
                                        AND name =  %s", self.session_id, fetchone=True )

            if result:
                #write(result[0][0])
                #Setting interval update, weather user checked to save his session
                self.lastEntrance = result[4]

                self.saveInterval = '336:00:00' if result[3] else self.saveInterval
                #Updating user's session
                self.psql.update( "session", {
                    'expire'      : ["localtimestamp + '" + self.saveInterval + "'::interval"],
                    'last_action' : ['localtimestamp'],
                    'location'    : self.environ['REQUEST_URI']

                }, "WHERE name = '%s'" % self.session_id )
                self.psql.commit()

                if result[1]:

                    r = self.psql.select( """SELECT u.id,u.login,u.email,u."group",                                  
                                 g.data, u."permissions" FROM "users" u
                                 LEFT JOIN groups g on (u."group" = g.id) 
                                 WHERE u.id = %s""", result[1], fetchone=True )

                    try:
                        if r:
                           data = {}
                           #data = r[0]
                           data['user_auth'] = True
                           data['SID'] = self.session_id

                           try:
                               perm = eval( r[4] )
                           except:
                               perm = {}
                               
                           user_permissions = {}
                           try:
                               user_permissions = eval( r[5] )
                               if isinstance(user_permissions, dict):
                                   perm.update(user_permissions)                                   
                           except:
                               pass
                            
                           data['permissions'] = perm

                           data['user_login'] = r[1]
                           data['user_id'] = r[0]
                           return data
                        else:

                           return self.default_result()
                    except:
                        return self.default_result()

                else: return self.default_result()
            else:
                #self.echo()
                #If no rows in database
                self.session_id = self.cookie.set( "session_id", self.id, 31104000 )
                self.insert_sess()

                return self.default_result()
        else:

            self.session_id = self.cookie.set( "session_id", self.id, 31104000 )
            #if not self.opera:  
            self.insert_sess()


            return self.default_result()

    #Inserting new session        
    def insert_sess( self ):

        self.psql.insert( "session", {
        'name'        : self.session_id,
        'expire'      : ["localtimestamp +  '" + self.saveInterval + "'::interval"],
        'last_action' : ['localtimestamp'],
        'location'    : self.environ['REQUEST_URI']
        } )

        self.psql.commit()
    #Build default result. To get session at the same moment
    def default_result( self ):
        permissions = self.psql.select( "SELECT data FROM \"groups\" WHERE name = 'guest'", fetchall=True )
        if permissions:
            #print permissions
            try:
                perm = eval( permissions[0][0] )

            except:
                perm = {}
        else:
            perm = {}

        return {'SID':self.session_id, 'user_auth':False, 'permissions':perm, 'user_id' : 0, 'session_user_name':''}






